import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:zentoon_flutter/providers/comic_provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../utils/http_helper.dart';
import '../../utils/user_manager.dart';
import '../../widgets/login_dialog.dart';
import '../../widgets/top_icon_bottom_text.dart';
import '../../providers/scroll_provider.dart'; // 导入滚动状态管理
import 'home_item.dart';
import 'model/home_banner_model.dart';

class HomeFirstScrren extends ConsumerStatefulWidget {
  final String categoryId;
  const HomeFirstScrren({super.key, required this.categoryId});

  @override
  ConsumerState<HomeFirstScrren> createState() => _HomeFirstScrrenState();
}

class _HomeFirstScrrenState extends ConsumerState<HomeFirstScrren>
    with AutomaticKeepAliveClientMixin {
  List<HomeBannerModel> imgList = [];
  bool _isDataLoaded = false;
  bool _isLoading = false;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _getBannerData();
    _handleAppTrack();
  }

  Future<void> _handleAppTrack() async {
    await AppTrackingTransparency.requestTrackingAuthorization();
  }

  @override
  void dispose() {
    super.dispose();
  }

  // 请求api，获取imgList的数据，GetComicBannerList，get请求
  Future<void> _getBannerData() async {
    // 如果数据已加载或正在加载中，直接返回
    if (_isDataLoaded || _isLoading) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    final userResponse = await HttpUtil().getModel<List<HomeBannerModel>>(
      'Comic/GetComicBannerList',
      fromJson: (json) =>
          (json as List).map((item) => HomeBannerModel.fromJson(item)).toList(),
    );

    if (userResponse?.status == 200 && userResponse?.result != null) {
      final banners = userResponse!.result!;
      setState(() {
        // 确保 imgList 保持正确的类型 List<HomeBannerModel>
        imgList = banners
            .where((banner) => banner.img != null && banner.img!.isNotEmpty)
            .toList();
        _isDataLoaded = true; // 标记数据已加载
        _isLoading = false;
      });
    } else {
      setState(() {
        _isLoading = false;
        // 可以选择是否设置默认数据
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      body: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification notification) {
          if (notification is ScrollUpdateNotification) {
            // 只监听垂直滚动，忽略水平滚动（CarouselSlider）
            if (notification.metrics.axis == Axis.vertical) {
              // 更新滚动偏移量到 Provider
              ref.read(scrollOffsetProvider.notifier).state =
                  notification.metrics.pixels;
            }
          }
          return false;
        },
        child: SingleChildScrollView(
          physics: const BouncingScrollPhysics(),
          child: Column(
            children: [
              Container(
                // 去掉背景色，避免影响全屏效果
                // color: Colors.amber,
                // 使用MediaQuery获取全屏尺寸
                height: MediaQuery.of(context).size.width * 165 / 375.0,
                width: MediaQuery.of(context).size.width,
                // 移除可能存在的内边距
                padding: EdgeInsets.zero,
                margin: EdgeInsets.zero,
                child: CarouselSlider(
                  items: imgList
                      .map((item) => GestureDetector(
                            onTap: () {
                              print("点击了banner");
                              if (item.id != null) {
                                context.pushNamed(
                                  'direct_reader',
                                  pathParameters: {
                                    'chapterId': item.link ?? '',
                                    'comicId': item.link ?? '',
                                  },
                                );
                              }
                            },
                            child: CachedNetworkImage(
                              imageUrl: item.img ?? '',
                              fit: BoxFit.cover,
                              width: MediaQuery.of(context).size.width,
                              height: MediaQuery.of(context).size.height,
                              placeholder: (context, url) => Container(
                                color: const Color(0xFF2A1F3D),
                                child: const Center(
                                  child: CircularProgressIndicator(
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                        Color(0xFF8A7CA8)),
                                    strokeWidth: 2.0,
                                  ),
                                ),
                              ),
                              errorWidget: (context, url, error) => Container(
                                color: const Color(0xFF2A1F3D),
                                child: const Center(
                                  child: Icon(
                                    Icons.broken_image,
                                    color: Color(0xFF8A7CA8),
                                    size: 48,
                                  ),
                                ),
                              ),
                              fadeInDuration: const Duration(milliseconds: 300),
                              fadeOutDuration:
                                  const Duration(milliseconds: 100),
                            ),
                          ))
                      .toList(),
                  options: CarouselOptions(
                    autoPlay: true,
                    aspectRatio: MediaQuery.of(context).size.width /
                        (MediaQuery.of(context).size.width * 0.7),
                    viewportFraction: 1.0,
                    enlargeCenterPage: false,
                    enableInfiniteScroll: true,
                    autoPlayInterval: const Duration(seconds: 3),
                    autoPlayAnimationDuration:
                        const Duration(milliseconds: 800),
                    autoPlayCurve: Curves.fastOutSlowIn,
                    clipBehavior: Clip.none,
                    // 添加滚动方向限制
                    scrollDirection: Axis.horizontal,
                    // 禁用用户手动滑动，只保留自动播放
                    // enableInfiniteScroll: true,
                    disableCenter: true,
                  ),
                ),
              ),
              Container(
                height: 100,
                margin:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    TopIconBottomText(
                      icon: Icons.calendar_today,
                      text: "Rewards",
                      backgroundColor: const Color(0xFF5AC8FA), // 蓝色
                      onTap: () async {
                        final isLoggedIn = await UserManager.isLoggedIn();
                        if (isLoggedIn) {
                          GoRouter.of(context).pushNamed('daily-checkin');
                        } else {
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) => const LoginDialog(),
                          );
                        }
                      },
                    ),
                    TopIconBottomText(
                      icon: Icons.verified,
                      text: "Premium",
                      backgroundColor: const Color(0xFF8E8AFF), // 紫色
                      onTap: () {
                        // 处理购买逻辑
                        if (context.mounted) {
                          final container = ProviderScope.containerOf(context);
                          container
                              .read(bottomNavIndexProvider.notifier)
                              .state = 2;
                        }
                      },
                    ),
                    TopIconBottomText(
                        icon: Icons.star,
                        text: "Frees",
                        backgroundColor: const Color(0xFFFF5ACD), // 粉色
                        onTap: () {
                          // 跳转到漫画列表页面
                          context.push('/manhua_list/0/1/Frees');
                        }),
                  ],
                ),
              ),
              Container(
                height: 10,
                width: double.infinity,
                color: Colors.white10,
              ),
              HomeContentWidget(isFirst: true, categoryId: widget.categoryId),
            ],
          ),
        ),
      ),
    );
  }
}
